﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Collections.ObjectModel;
using TaskHub.LocalStorage;
using TaskHub.EntityDataModel;
using System.Windows.Navigation;
using TaskHub.Controller;

namespace TaskHub
{
    public partial class MainPage : PhoneApplicationPage
    {

        #region Properties
        ApplicationDataController AppData = (Application.Current as App).AppData;
        private ucProgress _Progress;
        private ucProgress Progress
        {
            get
            {
                if (_Progress == null)
                {
                    _Progress = new ucProgress();
                }
                return _Progress;
            }
        }
        #endregion

        // Constructor
        public MainPage()
        {
            InitializeComponent();
            
            // Set the data context of the listbox control to the sample data
            DataContext = App.ViewModel;
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);

            TaskHub.wsTask.TaskSoapClient ws = new wsTask.TaskSoapClient();
            ws.GetMyTasksCompleted += new EventHandler<wsTask.GetMyTasksCompletedEventArgs>(ws_GetMyTasksCompleted);
            ws.GetOthersTasksCompleted += new EventHandler<wsTask.GetOthersTasksCompletedEventArgs>(ws_GetOthersTasksCompleted);

            ws.GetMyTasksAsync((uint)IsolatedStorageDAO.GetMyId());
            ws.GetOthersTasksAsync((uint)IsolatedStorageDAO.GetMyId());
        }

        void ws_GetMyTasksCompleted(object sender, wsTask.GetMyTasksCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                ObservableCollection<TaskHub.wsTask.TaskList> tasks = e.Result;
                foreach (TaskHub.wsTask.TaskList task in tasks)
                {
                    AppData.MyTasks.Add(new ItemViewModel()
                    {
                        TaskID = (int)task.TaskID,
                        OwnerAccountID = (int)task.OwnerAccountID,
                        TargetAccountID = (int)task.TargetAccountID,
                        TaskStatus = task.Status.ToString(),
                        LineOne = task.Name,
                        LineTwo = task.Description,
                        LineThree = task.DueDate.ToShortDateString(),
                    });
                }
                IsolatedStorageDAO.SaveMyTasks(AppData.MyTasks);
            }
        }

        void ws_GetOthersTasksCompleted(object sender, wsTask.GetOthersTasksCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                ObservableCollection<TaskHub.wsTask.TaskList> tasks = e.Result;
                foreach (TaskHub.wsTask.TaskList task in tasks)
                {
                    AppData.OtherTasks.Add(new ItemViewModel()
                    {
                        TaskID = (int)task.TaskID,
                        OwnerAccountID = (int)task.OwnerAccountID,
                        TargetAccountID = (int)task.TargetAccountID,
                        TaskStatus = task.Status.ToString(),
                        LineOne = task.Name,
                        LineTwo = task.Description,
                        LineThree = task.DueDate.ToShortDateString(),
                    });
                }
                IsolatedStorageDAO.SaveOtherTasks(AppData.OtherTasks);
            }
        }

        // Load data for the ViewModel Items
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (App.ViewModel.IsDataLoaded)
            {
                App.ViewModel.LoadData();
            }
        }      

        private void ContextMenuDeleteClick(object sender, RoutedEventArgs e)
        {
            var index = ((sender as MenuItem).DataContext as ItemViewModel);
            AppData.MyTasks.Remove(index);

            IsolatedStorageDAO.SaveMyTasks(AppData.MyTasks);
        }  

        private void AddNewTask(object sender, EventArgs e)
        {
            EuListBox.ItemsSource = null;
            EuListBox.ItemsSource = AppData.MyTasks;
            NavigationService.Navigate(new Uri("/NewTask.xaml", UriKind.Relative));
        }

        protected override void OnNavigatedTo(NavigationEventArgs args)
        {
            EuListBox.ItemsSource = AppData.MyTasks;
            TasksListBox.ItemsSource = AppData.MyTasks;
            HubListBox.ItemsSource = AppData.Contacts;

            LoadContactList();

            base.OnNavigatedTo(args);
        }

        public void LoadContactList()
        {
            try
            {
                wsContact.ContactSoapClient ws = new wsContact.ContactSoapClient();
                
                uint myId = 1;
                uint.TryParse(IsolatedStorageDAO.GetMyId().ToString(), out myId);

                ws.GetContactsCompleted += new EventHandler<wsContact.GetContactsCompletedEventArgs>(GetContactsCompletedWS);
                ws.GetContactsAsync(myId);
            }
            catch (Exception)
            {
                return;
            }
        }

        public void GetContactsCompletedWS(object sender, wsContact.GetContactsCompletedEventArgs e)
        {
            try
            {
                if (e != null && e.Result != null)
                {
                    var contacts = new ObservableCollection<wsContact.ContactList>();
                    var contactList = ConvertToContactView(e.Result);
                    if (contactList != null)
                    {
                        AppData.Contacts = contactList;
                        IsolatedStorageDAO.SaveContacs(AppData.Contacts);
                        HubListBox.ItemsSource = AppData.Contacts;
                    }
                }
            }
            catch (Exception)
            {
                return;
            }
            
        }

        private ObservableCollection<ItemViewModel> ConvertToContactView(ObservableCollection<wsContact.ContactList> contactList)
        {
            var listContacts = new ObservableCollection<ItemViewModel>();
            if (contactList != null && contactList.Count > 0)
            {
                foreach (var item in contactList)
                {
                    listContacts.Add(new ItemViewModel() {
                        LineOne = item.Name,
                        LineTwo = item.ContactID.ToString(),
                        contactAccountId = (int) item.ContactID,
                        contactName = item.Name
                    });
                }
            }
            return listContacts;
        }

        private void settigns_Click(object sender, EventArgs e)
        {
            try
            {
                NavigationService.Navigate(new Uri("/Settings.xaml", UriKind.Relative));
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
            }
        }

        private void ContextMenu_Loaded(object sender, RoutedEventArgs e)
        {
            var item = ((sender as MenuItem).DataContext as ItemViewModel);
            if (item.TaskStatus.CompareTo("0") != 0) {
                //
            }
        }

        private void ContextMenuAcceptClick(object sender, RoutedEventArgs e)
        {
            var item = ((sender as MenuItem).DataContext as ItemViewModel);
        }

        private void ContextMenuRejectClick(object sender, RoutedEventArgs e)
        {

        }

        private void ContextMenuCompleteClick(object sender, RoutedEventArgs e)
        {
            var item = ((sender as MenuItem).DataContext as ItemViewModel);

            TaskHub.wsTask.TaskSoapClient ws = new wsTask.TaskSoapClient();
            ws.CompleteTaskCompleted += new EventHandler<wsTask.CompleteTaskCompletedEventArgs>(ws_CompleteTaskCompleted);
            ws.CompleteTaskAsync((uint) IsolatedStorageDAO.GetMyId(), (uint) item.TaskID);

            AppData.MyTasks.Remove(item);
            IsolatedStorageDAO.SaveMyTasks(AppData.MyTasks);
        }

        void ws_CompleteTaskCompleted(object sender, wsTask.CompleteTaskCompletedEventArgs e)
        {
            // Something bad happened!!! //
            if (e.Error != null)
            {
                //MessageBox.Show("Could not update the new Task", "Error", MessageBoxButton.OK);
                //return;
            }

            uint TaskID = (uint)e.Result;
            if (TaskID == 0)
            {
                MessageBox.Show("Could not update the new Task", "Error", MessageBoxButton.OK);
                return;
            }

            // Remove from the list //
            foreach (ItemViewModel item in AppData.MyTasks) {
                if (item.TaskID == TaskID) {
                    AppData.MyTasks.Remove (item);
                }
            }
            IsolatedStorageDAO.SaveMyTasks(AppData.MyTasks);
        }
    }
}